#!/bin/bash
# ------------------------------------------
# 安全版 git-pr.sh
# 自动提交修改 + 同步上游 + 推送到 Fork
# ------------------------------------------

if [ $# -eq 0 ]; then
  echo "❗️请提供本次修改描述，例如："
  echo "./git-pr.sh \"修复 addUser 空指针异常\""
  exit 1
fi

DESCRIPTION="$1"
DATE_TAG=$(date +%Y%m%d%H%M%S)
FEATURE_BRANCH="feature-${DATE_TAG}"

echo "🚀 [1/6] 检查当前 Git 状态..."
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "❌ 当前目录不是 Git 仓库！"
  exit 1
fi

echo "🔍 当前分支: $(git branch --show-current)"
CURRENT_BRANCH=$(git branch --show-current)

# ------------------------------------------
# 保存未提交修改，防止 rebase 时丢失
# ------------------------------------------
echo "💾 [2/6] 提交本地修改（如有）..."
git add .
if git diff --cached --quiet; then
  echo "✅ 无需提交，本地无修改。"
else
  git commit -m "$DESCRIPTION"
fi

# ------------------------------------------
# 如果当前在 master，则创建新分支开发
# ------------------------------------------
if [ "$CURRENT_BRANCH" = "master" ]; then
  echo "🛡️ 当前在 master，自动创建开发分支 $FEATURE_BRANCH ..."
  git checkout -b $FEATURE_BRANCH
  CURRENT_BRANCH=$FEATURE_BRANCH
else
  echo "🛠️ 当前在分支 $CURRENT_BRANCH，将直接使用此分支。"
fi

# ------------------------------------------
# 同步上游仓库
# ------------------------------------------
echo "🌍 [3/6] 同步上游 master..."
git fetch upstream
git checkout master
git rebase upstream/master || {
  echo "⚠️ rebase 失败，尝试自动恢复..."
  git rebase --abort
  echo "请手动解决冲突后再运行脚本。"
  exit 1
}
git checkout $CURRENT_BRANCH
git rebase master

# ------------------------------------------
# 推送到远程 Fork
# ------------------------------------------
echo "☁️ [4/6] 推送分支到远程 Fork..."
git push origin HEAD -f || {
  echo "❌ 推送失败，请检查网络或权限。"
  exit 1
}

# ------------------------------------------
# 打印 PR 提示
# ------------------------------------------
echo "✅ [5/6] 推送完成，本次修改描述: $DESCRIPTION"
USERNAME=$(git remote get-url origin | sed -n 's#.*gitee.com/\(.*\)/.*#\1#p' | cut -d'/' -f1)
REPO=$(git remote get-url origin | sed -n 's#.*/\([^/]*\)\.git#\1#p')

echo "🌐 [6/6] 你现在可以前往 Gitee 发起 PR："
echo "👉 https://gitee.com/${USERNAME}/${REPO}/compare/${CURRENT_BRANCH}...master"

echo "🎉 操作完成！"
